package com.ptszyxx.popose.module.main.mine.vm;

import android.app.Application;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import com.alibaba.fastjson.JSONObject;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ptszyxx.popose.common.utils.YBusUtil;
import com.ysg.base.BaseViewModel;
import com.ysg.binding.command.BindingCommand;
import com.ysg.bus.event.SingleLiveEvent;
import com.ysg.http.BaseResponse;
import com.ysg.http.HttpUtils;
import com.ysg.http.callback.OnSuccessResult;
import com.ysg.http.data.CommonRepository;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MineRealVM extends BaseViewModel<CommonRepository> {
    public ObservableField<String> name = new ObservableField<>();
    public ObservableField<String> code = new ObservableField<>();
    public String access_token;

    public MineRealVM(@NonNull Application application, CommonRepository model) {
        super(application, model);
    }

    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        public SingleLiveEvent onFaceEvent = new SingleLiveEvent<>();
    }

    public BindingCommand onSubmitCommand = new BindingCommand(()-> onNext());

    //=========================================接口：start===========================================
    /**
     *
     */
    public void requestRealSave(String image){
        if (YStringUtil.isEmpty(name.get())){
            YToastUtil.showShort(R.string.mine_real_name_hint);
            return;
        }
        if (YStringUtil.isEmpty(code.get())){
            YToastUtil.showShort(R.string.mine_real_code_hint);
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("realName", name.get());
        map.put("idNum", code.get());
//        map.put("image", image);
        HttpUtils.getInstance()
                .data(model.realSaveIos(map), this,
                        new OnSuccessResult() {
                            @Override
                            public void onSuccessResult(BaseResponse response) {
                                YToastUtil.showShort(response.getMsg());
                                YActivityUtil.getInstance().close(MineRealVM.this);
                                YBusUtil.userEdit();
                            }
                        });
    }

    /**
     *
     */
    public void requestAccessToken(){
//        Map<String, String> map = new HashMap<>();
//        HttpUtils.getInstance()
//                .data(model.realToken(map), this,
//                        new OnSuccessResult<String>() {
//                            @Override
//                            public void onSuccessResult(BaseResponse<String> response) {
//                                access_token = response.getData();
//                            }
//                        });
        new Thread(()->{
            String ak = "6VDiUPHp4QbFmBGzscAsG7i4";
            String sk = "4WrfNF659RGwben3ysWR0nv8Nc87eI3r";
            String url = "https://aip.baidubce.com/oauth/2.0/token?client_id="+ak+"&client_secret="+sk+"&grant_type=client_credentials";
            Request request = new Request.Builder().url(url).build();
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .build();
            try {
                StringBuilder sb = new StringBuilder();
                Response response = okHttpClient.newCall(request).execute();
                if (response != null && 200 == response.code()){
                    InputStream is = response.body().byteStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader reader = new BufferedReader(isr);
                    String jsonLine;
                    while ((jsonLine = reader.readLine()) != null) {
                        sb.append(jsonLine);
                    }
                    reader.close();
                    isr.close();
                    is.close();

                    Log.e("result", sb.toString());

//                    {
//                        "refresh_token": "25.eb255ae20c240bf9fec54eccd778fa77.315360000.2014769173.282335-35104679",
//                            "expires_in": 2592000,
//                            "session_key": "9mzdWTk/tjZznYtdhlK8X5AlRyLr0fOKWTzBtiVCHhkxuZpenIPfuQs7P9OvZ/2mP1Be0UPa5vwzJQ34yVE/z4M4BLT71w==",
//                            "access_token": "24.bc13a9f9dc584a17768e2f7bbab72848.2592000.1702001173.282335-35104679",
//                            "scope": "public vis-ocr_ocr brain_all_scope brain_ocr_idcard vis-faceverify_faceverify_h5-face-liveness vis-faceverify_FACE_V3 vis-faceverify_FACE_Police vis-faceverify_idl_face_merge vis-faceverify_FACE_EFFECT vis-faceverify_face_beauty vis-faceverify_face_feature_sdk brain_phone_verify brain_face_scene_scope brain_在线图片活体检测 wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx",
//                            "session_secret": "eac2efe5f73a7dcf44ab7eaa4390b5b4"
//                    }

                    JSONObject jsonObject = JSONObject.parseObject(sb.toString());
                    access_token = jsonObject.getString("access_token");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void onNext(){
        if (YStringUtil.isEmpty(name.get())){
            YToastUtil.showShort(R.string.mine_real_name_hint);
            return;
        }
        if (YStringUtil.isEmpty(code.get())){
            YToastUtil.showShort(R.string.mine_real_code_hint);
            return;
        }
        uc.onFaceEvent.call();
    }






}
